package com.jsj.servlet.ch2;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 * 注解
 */
@WebServlet(urlPatterns="/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	
    public HelloServlet() {
        super();
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 * init方法用于在创建Servlet时进行初始化工作，比如连接数据库等等
	 * init方法只是在服务器创建Servlet时执行一次
	 * Servlet第一次被访问的时候执行init方法
	 * 
	 */    
	public void init(ServletConfig config) throws ServletException {
		System.out.println(this.getClass().getName()+"的init方法开始执行！");
	}

	/**
	 * @see Servlet#destroy()
	 * destroy方法在服务器关闭的情况下执行一次
	 * 工作可以有：关闭数据库连接或者其他资源等
	 * 
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println(this.getClass().getName()+"的destroy方法开始执行！");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 * 用于响应get方式提交的请求
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println("<html>");
		out.println("<head><title>my first Servlet</title></head>");
		out.println("<body><p style='color:red;'>hello</p></body>");
		out.println("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 * 用于响应post方式提交的请求
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
